package com.jf.blog.util.interceptor;

import com.jf.blog.util.MyConstants;
import com.jf.blog.util.exception.BusinessException;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader(MyConstants.TOKEN);
        if (StringUtils.isEmpty(token)) {
            throw new BusinessException(401, "未携带token！");
        }
        String value = redisTemplate.opsForValue().get(MyConstants.TOKEN_KEY + token);
        if (StringUtils.isEmpty(value)) {
            throw new BusinessException(401, "登录失效！");
        }
        return true;
    }
}
